import store from '../store'
import axios from 'axios'
import { message } from 'antd'
import { history } from '@/utils'
import { clearInfo } from '@/store/actions'
const baseURL =
  process.env.NODE_ENV === 'development' ? '/api' : process.env.REACT_APP_URL
const http = axios.create({
  // baseURL: 'http://geek.itheima.net/v1_0',
  // baseURL: 'http://toutiao.itheima.net/v1_0',
  baseURL,
  timeout: 5000,
})
export { http }
// 请求拦截器
http.interceptors.request.use((config) => {
  const { login: token } = store.getState()
  if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
// 响应拦截器
http.interceptors.response.use(undefined, (error) => {
  if (!error.response) {
    message.error('网络繁忙')
    return Promise.reject(error)
  }
  if (error.response.status === 401) {
    message.error('登录超时', 1, () => {
      store.dispatch(clearInfo())
      history.push('/login', { from: history.location.pathname })
    })
  }
  return Promise.reject(error)
})
